#!/bin/sh
# c2reader: a reader for c2wiki articles (see wiki.c2.com)
# usage: c2reader <ArticleName>
c2read() {
	case `$CLIENT $FLAGS https://proxy.c2.com/wiki/remodel/pages/$page` in
	*404*)	echo '404: page not found'; exit 2 ;;
	esac
	$CLIENT $FLAGS https://proxy.c2.com/wiki/remodel/pages/$page | jq '.text' | sed 's/\\r\\n/\
	/g' | less
}

CLIENT=curl
CURL_FLAGS='-s'
OBSD_FTP_FLAGS='-V -o'

case $CLIENT in
curl)	FLAGS=$CURL_FLAGS ;;
ftp)	FLAGS=$OBSD_FTP_FLAGS ;;
esac


case $# in
1) page=$1 c2read $CLIENT $FLAGS $page; exit
esac

printf 'What do you want to do?\n1)read\n2)search\n'
read -r task
case $task in 
1)	echo 'What page do you want to read?'
	read -r page
	c2read $CLIENT $FLAGS $page
	;;
2)	echo 'Enter search term:'
	read -r query
	echo 'showing top 10 results'
	$CLIENT $FLAGS https://c2.com/cgi/fullSearch?search=$query |xmllint --html --xpath "//a/@href" - | cut -d '"' -f2 | sed 's/wiki?//' | head | nl
        echo 'What page would you like to read?'
        read -r page
	c2read $CLIENT $FLAGS $page
esac
